package com.example.hello.config;

import io.minio.BucketExistsArgs;
import io.minio.MinioClient;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class ObjectStorageInitializer implements CommandLineRunner {

    private static final Logger logger = LogManager.getLogger(ObjectStorageInitializer.class);

    @Autowired
    private MinioClient minioClient;

    @Value("${object.storage.bucket-name}")
    private String bucketName;
    
    @Value("${storage.type:local}")
    private String storageType;

    @Override
    public void run(String... args) throws Exception {
        // 如果不使用对象存储，则跳过初始化
        if (!"object".equalsIgnoreCase(storageType)) {
            logger.info("当前存储类型为 {}，跳过对象存储初始化", storageType);
            return;
        }
        
        logger.info("开始初始化对象存储，存储桶名称: {}", bucketName);
        
        try {
            // 检查存储桶是否存在
            boolean bucketExists = minioClient.bucketExists(
                BucketExistsArgs.builder()
                    .bucket(bucketName)
                    .build()
            );

            if (bucketExists) {
                logger.info("存储桶 {} 已存在", bucketName);
            } else {
                logger.warn("存储桶 {} 不存在，但无法创建（可能没有足够权限）", bucketName);
                logger.info("请确保 Sealos 中已经创建了名为 {} 的存储桶，并设置了正确的访问策略", bucketName);
            }
        } catch (Exception e) {
            logger.error("检查存储桶失败: {}", e.getMessage());
            logger.info("请确保 Sealos 中已经创建了名为 {} 的存储桶，并设置了正确的访问策略", bucketName);
            // 不抛出异常，允许应用继续启动
        }
    }
} 